<template>
  <!-- 短信登录 -->
  <div class="message-container">
    <el-form-item label="手机号" prop="phone">
      <el-input type="text" maxlength="11" v-model="phone"></el-input>
      <span class="captcha" @click="sendMessage" v-text="msg">
        点击发送验证码
      </span>
    </el-form-item>

    <el-form-item label="验证码">
      <el-input type="text" v-model="code"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" class="sumbit-captcha" @click="sumbitCode">
        提交
      </el-button>
    </el-form-item>
  </div>
</template>
<script>
import * as api from "@/api/users";
export default {
  props: {
    storageUserInfo: {
      required: true,
    },
  },
  data() {
    return {
      msg: "点击发送验证码",
      flag: true, //解决双击 秒数重新--问题
      phone: "", //手机号
      code: "", //短信验证码
    };
  },
  methods: {
    async sendMessage() {
      if (this.flag) {
        this.flag = false;
        // 获取手机短信验证码
        let res = await api.getMessage(this.phone);
        console.log(res);
        // 短信发送成功
        if (res.data.state) {
          this.$message({
            message: "短信发送成功",
            type: "success",
          });
        } else {
          this.$message.error(res.data.msg);
        }
        let second = 5;
        this.msg = `${second}秒后重新发送`;
        this.interval = setInterval(() => {
          second--;
          if (second < 1) {
            this.msg = "点击发送验证码";
            clearInterval(this.interval);
            this.flag = true;
          } else {
            this.msg = `${second}秒后重新发送`;
          }
        }, 1000);
      }
    },
    async sumbitCode() {
      let res = await api.getMessageLogin(this.code);
      console.log(res);
      // 存储用户信息
      this.storageUserInfo(res.data);
      // 跳转页面
      this.$router.push("/");
    },
  },
};
</script>

<style lang="less" scoped>
.el-input {
  width: 260px;
}
/deep/.el-form-item__label {
  color: white;
  padding: 2px 14px 0 0;
}
.message-container {
  position: relative;
  .captcha {
    position: absolute;
    left: 146px;
    color: rgb(136, 136, 136);
    cursor: pointer;
    user-select: none;
  }
}
.sumbit-captcha {
  width: 260px;
  margin-top: 15px;
}
</style>
